package com.example.common.utils;

import com.alibaba.fastjson.JSON;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.net.URLEncoder;

@Component
public class QiniuUtils {

//    也可以去yaml文件中的值
    //修改以下两个值放到proprietarties中，在密钥管理中获取
    @Value("${qiniu.accessKey}")
    private String accessKey;
    @Value("${qiniu.accessSecretKey}")
    private String accessSecretKey;
    @Value("${qiniu.url}")
    private String url;
    @Value("${qiniu.bucket}")
    private String bucket;

    public boolean upload(MultipartFile file, String fileName ,String wenjianj){

        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.huanan());//注意不同的地区（eg：华东区）
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上传凭证，然后准备上传，修改上传名称为自己创立空间的空间名称（是你自己的）

        //默认不指定key的情况下，以文件内容的hash值作为文件名
        try {
            byte[] uploadBytes = file.getBytes();
            Auth auth = Auth.create(accessKey, accessSecretKey);
            String upToken = auth.uploadToken(bucket);
            Response response = uploadManager.put(uploadBytes, wenjianj+fileName, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);
            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return false;
    }

    /*
    * 存在问题
    * */
    public String download(String fileName,String wenjianj) throws Exception {
        //七牛云上存储文件生成的文件名
        String encodedFileName = URLEncoder.encode(fileName, "utf-8").replace("+", "%20");
        String publicUrl = String.format("%s%s%s", url, wenjianj , encodedFileName);
        Auth auth = Auth.create(accessKey, accessSecretKey);
        //失效时间
        long expireInSeconds = 3600;
        String finalUrl = auth.privateDownloadUrl(publicUrl, expireInSeconds);
        return finalUrl;
    }

    public boolean delete(String fileName ,String wenjian){
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.region0());
        //...其他参数参考类注释
        Auth auth = Auth.create(accessKey, accessSecretKey);
        BucketManager bucketManager = new BucketManager(auth, cfg);
        String fileurl=wenjian+fileName;
        try {

            bucketManager.delete(bucket, fileurl);
            return true;
        } catch (Exception ex) {
            return false;
        }
    }

}
